package com.dean.pokeking.ui.pages

import android.graphics.BitmapFactory
import android.util.Log
import android.widget.ImageButton
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.dean.pokeking.MainApplication
import com.dean.pokeking.beans.MonsterButton
import com.dean.pokeking.beans.MonsterList
import com.dean.pokeking.beans.PlayerList
import com.dean.pokeking.repository.NpcDataRepository
import com.dean.pokeking.ui.MainViewModel
import kotlinx.coroutines.runBlocking
import kotlin.math.ceil

/**
 * @ClassName NpcTeamInfoPage
 * @Description NpcTeamInfoPage
 * @Author Dean
 * @Date 2023/3/23
 * @Version 1.0
 */

@Composable
fun NpcTeamInfoPage() {
    val viewModel = viewModel<MainViewModel>()
    val mainState = viewModel.mainState.collectAsState().value
    val currentNpc = mainState.currentNpc
    val filterMonsterList = mainState.filterMonsterList
    val lineupList = mainState.npcLineup
    var monsterEditorVisible by remember { mutableStateOf(false) }
    var editPlayerList by remember { mutableStateOf(PlayerList()) }
    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
            .background(color = Color.Gray.copy(alpha = 0.3f))
    ) {
        items(items = lineupList, key = { it.id ?: "$it" }) {
            var selectIndex by remember {
                var finalIndex = 0
                for (index in it.playerList.indices) {
                    if (filterMonsterList.isNotEmpty()) {
                        if (it.playerList[index].name == filterMonsterList[0].name) {
                            finalIndex = index
                            break;
                        }
                    }
                }
                mutableStateOf(finalIndex)
            }
            Column {
                Spacer(modifier = Modifier.height(5.dp))
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 10.dp)
                ) {
                    Text(
                        modifier = Modifier
                            .background(Color.White)
                            .border(2.dp, Color.Black, RoundedCornerShape(5.dp))
                            .padding(5.dp),
                        text = "${it.idx}",
                        fontSize = 22.sp
                    )
                    Spacer(modifier = Modifier.weight(1f))
                    Text(
                        modifier = Modifier
                            .background(Color.White)
                            .border(2.dp, Color.Black, RoundedCornerShape(5.dp))
                            .padding(5.dp)
                            .clickable {
                                editPlayerList = it.playerList[selectIndex]
                                monsterEditorVisible = true
                            },
                        text = "修订",
                        fontSize = 22.sp
                    )
                }
                Spacer(modifier = Modifier.height(5.dp))
                TeamInfoCard(selectIndex = selectIndex, playerList = it.playerList) {
                    selectIndex = it
                }
            }
        }
        item {
            Spacer(modifier = Modifier.height(60.dp))
        }
    }

    if (mainState.showFilterPage) {
        MonsterFilterPage(
            monsters = mainState.npcMonsterButtonList,
            filter = mainState.filterMonsterList,
            shouldShow = viewModel::shouldShow,
            onButtonClick = { name, addOrRemove ->
                if (addOrRemove) viewModel.addFilterMonster(name) else viewModel.removeFilterMonster(
                    name
                )
            }
        )
    }

    if (monsterEditorVisible) {
        MonsterEditPage(
            editPlayerList = editPlayerList
        ) {
            monsterEditorVisible = false
            Log.d("test", "id: ${it.id}, note: ${it.note}")
            viewModel.savePlayer(it)
        }
    }
}


@Composable
fun MonsterFilterPage(
    monsters: List<MonsterButton>,
    filter: List<MonsterList>,
    shouldShow: (name: String) -> Boolean,
    onButtonClick: (name: String, addOrRemove: Boolean) -> Unit
) {
    Box(
        modifier = Modifier.padding(bottom = 50.dp).background(color = Color.White)
    ) {
        GridLayout(
            columns = 4,
            items = monsters
        ) {
            if (shouldShow(it.monsterName)) {
                val isInFilter = filter.find { monster -> monster.name == it.monsterName } != null
                MyImageButton(
                    name = it.monsterName,
                    isInFilter = isInFilter
                ) {
                    onButtonClick(it.monsterName, !isInFilter)
                }
            }
        }
    }
}

@Composable
fun MyImageButton(
    name: String,
    isInFilter: Boolean,
    onClick: () -> Unit,
) {
    val bitmap = runCatching {
        val file =
            LocalContext.current.assets.open("monsters/${name}.png")
        BitmapFactory.decodeStream(file).asImageBitmap()
    }.getOrNull()
    if (bitmap != null) {
        IconButton(
            modifier = Modifier
                .background(color = if (isInFilter) Color.Yellow else Color.White.copy(blue = 0.9f))
                .size(80.dp),
            onClick = onClick
        ) {
            Image(bitmap = bitmap, contentDescription = "")
        }
    } else {
        Button(onClick = onClick) {
            Text(text = name)
        }
    }
}

@Composable
fun <T> GridLayout(
    modifier: Modifier = Modifier,
    columns: Int,
    items: List<T>,
    content: @Composable (T) -> Unit
) {
    val rows = ceil(items.size.toFloat() / columns).toInt()
    LazyColumn(modifier = modifier) {
        items(rows) { rowIndex ->
            Row {
                repeat(columns) { columnIndex ->
                    val index = rowIndex * columns + columnIndex
                    if (index < items.size) {
                        Box(
                            Modifier
                                .weight(1f)
                                .padding(4.dp)
                        ) {
                            content(items[index])
                        }
                    } else {
                        Spacer(
                            Modifier
                                .weight(1f)
                                .padding(4.dp)
                        )
                    }
                }
            }
        }
    }
}


@Composable
fun TeamInfoCard(
    selectIndex: Int = 0,
    playerList: List<PlayerList>?,
    onIndexChange: (Int) -> Unit = {}
) {
    Column(
        modifier = Modifier.fillMaxWidth()
    ) {
        TabRow(selectedTabIndex = selectIndex) {
            playerList?.forEachIndexed { index, playerList ->
                Tab(
                    modifier = Modifier.padding(5.dp),
                    selected = selectIndex == index,
                    onClick = { onIndexChange(index) }
                ) {
                    val bitmap = runCatching {
                        val file =
                            LocalContext.current.assets.open("monsters/${playerList.name}.png")
                        BitmapFactory.decodeStream(file).asImageBitmap()
                    }.getOrNull()
                    if (bitmap != null) {
                        Image(bitmap = bitmap, contentDescription = "")
                    } else {
                        Text(text = playerList.name ?: "未知精灵")
                    }
                }
            }
        }
        Text(
            modifier = Modifier
                .background(color = Color.Blue.copy(alpha = 0.2f))
                .fillMaxWidth(),
            text = playerList?.get(selectIndex)?.name ?: "",
            textAlign = TextAlign.Center,
            fontSize = 20.sp
        )
        Card(
            modifier = Modifier
                .background(color = Color.Gray.copy(alpha = 0.3f))
                .fillMaxWidth()
                .padding(8.dp)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(8.dp)
            ) {
                Column(modifier = Modifier.weight(0.5f)) {
                    BorderedText(
                        text = (playerList?.get(selectIndex)?.firstAttribute
                            ?: "") + "/" + (playerList?.get(selectIndex)?.secondAttribute ?: "")
                    )
                    BorderedText(text = playerList?.get(selectIndex)?.characteristic ?: "")
                    BorderedText(text = playerList?.get(selectIndex)?.prop ?: "")
                    BorderedText(
                        text = playerList?.get(selectIndex)?.skillA ?: "",
                        backGroundColor = Color.Green.copy(alpha = 0.3f)
                    )
                    BorderedText(
                        text = playerList?.get(selectIndex)?.skillB ?: "",
                        backGroundColor = Color.Green.copy(alpha = 0.3f)
                    )
                    BorderedText(
                        text = playerList?.get(selectIndex)?.skillC ?: "",
                        backGroundColor = Color.Green.copy(alpha = 0.3f)
                    )
                    BorderedText(
                        text = playerList?.get(selectIndex)?.skillD ?: "",
                        backGroundColor = Color.Green.copy(alpha = 0.3f)
                    )
                }
                Spacer(modifier = Modifier.width(5.dp))
                Box(
                    modifier = Modifier
                        .border(2.dp, Color.Black, RoundedCornerShape(5.dp))
                        .background(color = Color.Yellow.copy(alpha = 0.3f))
                        .weight(1f)
                        .padding(5.dp)
                        .height(IntrinsicSize.Max),
                    contentAlignment = Alignment.Center
                ) {
                    val notes = playerList?.get(selectIndex)?.note?.split("|")
                    Text(text = notes?.get(notes.lastIndex) ?: "", fontSize = 25.sp)
                }
            }
        }
    }
}

@Composable
fun BorderedText(
    text: String,
    backGroundColor: Color = Color.White,
) {
    Text(
        modifier = Modifier
            .background(color = backGroundColor)
            .border(2.dp, Color.Black, RoundedCornerShape(4.dp))
            .fillMaxWidth()
            .padding(horizontal = 4.dp, vertical = 1.dp),
        text = text,
        fontSize = 18.sp
    )
    Spacer(modifier = Modifier.height(2.dp))
}